import request from '../../utils/request';

// pages/level-select/level-select.js
Page({
  data: {
    userInfo: {},
    difficulties: [
      {
        id: 'beginner',
        name: '初级',
        // 看图猜成语 初级通关描述 
        desc: '在这里，你将通过生动有趣的图片，解锁一个个经典的成语故事。每一张图片都暗藏玄机，仔细观察，开动脑筋，你就能发现其中的奥秘！',
        color: '#10B981',
        icon: '/assets/images/level_beginner.png',
        unlocked: true,
        levels: []
      },
      {
        id: 'intermediate',
        name: '中级',
        desc: '你已经通过了初级关卡的考验，现在是时候展现真正的实力了！中级关卡将带你进入更丰富的成语世界，图片更复杂，成语更巧妙，快来接受挑战吧！',
        color: '#F59E0B',
        icon: '/assets/images/level_intermediate.png',
        unlocked: false,
        requiredLevel: 5,
        levels: []
      },
      {
        id: 'advanced',
        name: '高级',
        desc: '你已经通过了初级和中级关卡的考验，现在是时候挑战最高难度了！高级关卡将带你进入成语的深邃世界，图片暗藏玄机，成语寓意深远，只有真正的成语大师才能通关！',
        color: '#EF4444',
        icon: '/assets/images/level_advanced.png',
        unlocked: false,
        requiredLevel: 5,
        levels: []
      }
    ],
    currentDifficulty: 0
  },

  onLoad: function (options) {
    // 如果有传入的难度参数，切换到对应难度
    if (options.difficulty) {
      const index = this.data.difficulties.findIndex(d => d.id === options.difficulty);
      if (index !== -1) {
        this.setData({
          currentDifficulty: index
        });
      }
    }
    
    // 从 app.globalData.userInfo 获取已完成的关卡
    const app = getApp();
    const completedLevels = app.globalData.userInfo?.completedLevels || [];
    this.setData({ completedLevels });

    // 加载所有难度的关卡数据
    this.data.difficulties.forEach((_, index) => {
      this.loadLevels(index);
    });
  },

  onShow: function () {
    // 获取用户信息
    const app = getApp();
    if (app.globalData.userInfo) {
      this.setData({
        userInfo: app.globalData.userInfo,
        completedLevels: app.globalData.userInfo.completedLevels || []
      });

      // 加载所有难度的关卡数据
      this.data.difficulties.forEach((_, index) => {
        this.loadLevels(index);
      });
    }
  },

  /**
   * 加载指定难度的关卡数据
   * @param {number} difficultyIndex - 难度索引(0:初级, 1:中级, 2:高级)
   */
  loadLevels: function (difficultyIndex) {
    const difficulty = this.data.difficulties[difficultyIndex];
    const difficultyMap = {
      'beginner': 'beginner_',
      'intermediate': 'intermediate_',
      'advanced': 'advanced_'
    };
    const difficultyPrefix = difficultyMap[difficulty.id];

    request({
      url: '/levels',
      method: 'GET'
    })
      .then(res => {
        // 确保获取 list 数组
        const levelsData = res.data.list || [];

        // 过滤当前难度的关卡
        const difficultyLevels = levelsData.filter(level => 
          level.id.startsWith(difficultyPrefix)
        );

        // 处理关卡数据
        const processedLevels = difficultyLevels
          .sort((a, b) => a.order - b.order) // 确保按order排序
          .map((level, index) => {
            // 解析options字符串为数组
            let options = [];
            try {
              options = JSON.parse(level.options);
            } catch (e) {
              console.error('解析options失败:', level.options);
              options = [];
            }

            // 判断关卡状态
            const isCompleted = this.data.completedLevels.includes(level.id);
            const isUnlocked = this.checkLevelUnlocked(level, index, difficultyIndex);

            return {
              ...level,
              options,
              isCompleted,
              isUnlocked
            };
          });

        // 更新当前难度的关卡数据
        const difficulties = this.data.difficulties;
        difficulties[difficultyIndex].levels = processedLevels;
        
        // 更新难度解锁状态
        if (difficultyIndex > 0) {
          const prevDifficulty = difficulties[difficultyIndex - 1];
          const prevDifficultyPrefix = difficultyMap[prevDifficulty.id];
          const completedPrevLevels = this.data.completedLevels.filter(id =>
            id.startsWith(prevDifficultyPrefix)
          ).length;

          difficulties[difficultyIndex].unlocked =
            completedPrevLevels >= difficulties[difficultyIndex].requiredLevel;
          difficulties[difficultyIndex].progress = completedPrevLevels;
          difficulties[difficultyIndex].total = difficulties[difficultyIndex].requiredLevel;
        }

        this.setData({ difficulties });
      })
      .catch(err => {
        console.error('加载关卡失败:', err);
        wx.showToast({
          title: '加载关卡失败',
          icon: 'none'
        });
      });
  },

  /**
   * 检查关卡是否解锁
   * @param {Object} level - 当前关卡
   * @param {number} index - 关卡索引
   * @param {number} difficultyIndex - 难度索引
   */
  checkLevelUnlocked: function (level, index, difficultyIndex) {
    // 初级难度第一关默认解锁
    if (difficultyIndex === 0 && index === 0) return true;

    // 其他难度需要满足前置条件
    if (difficultyIndex > 0) {
      const prevDifficulty = this.data.difficulties[difficultyIndex - 1];
      const completedPrevLevels = this.data.completedLevels.filter(id =>
        id.startsWith(`difficulty${prevDifficulty.id}_`)
      ).length;

      // 检查是否满足解锁当前难度所需关卡数
      if (!prevDifficulty.unlocked ||
        completedPrevLevels < prevDifficulty.requiredLevels) {
        return false;
      }
    }

    // 当前难度内的关卡解锁逻辑
    if (index === 0) {
      // 当前难度第一关，只要难度解锁了就解锁
      return this.data.difficulties[difficultyIndex].unlocked;
    } else {
      // 其他关卡需要前一关已完成
      const prevLevelId = this.data.difficulties[difficultyIndex].levels[index - 1]?.id;
      return this.data.completedLevels.includes(prevLevelId);
    }
  },

  // 切换难度
  switchDifficulty: function (e) {
    const index = e.currentTarget.dataset.index;
    this.setData({
      currentDifficulty: index
    });
  },

  // 开始游戏
  startGame: function (e) {
    const levelIndex = e.currentTarget.dataset.index;
    const difficulty = this.data.difficulties[this.data.currentDifficulty];
    const level = difficulty.levels[levelIndex];

    if (!difficulty.unlocked) {
      wx.showToast({
        title: `需要完成${difficulty.total}关${this.data.currentDifficulty === 1 ? '初级' : '中级'}才能解锁`,
        icon: 'none'
      });
      return;
    }

    if (!level.isUnlocked) {
      wx.showToast({
        title: '请先完成前面的关卡',
        icon: 'none'
      });
      return;
    }

    wx.navigateTo({
      url: `/pages/game/game?level_id=${level.id}`
    });
  },

  // 返回上一页
  navigateBack: function () {
    wx.navigateBack();
  }
});